package br.ufrgs.inf.engsoft.stp.persistence;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Dao abstrato.
 *
 * @author mauricio.quatrin
 */

public abstract class AbstractDao<T, PK extends Serializable> {
    private Session session = HibernateUtil.getSessionFactory().openSession();
    private Transaction tx;
    
    protected void create(Object obj) {
        tx = session.beginTransaction();
        try {
            session.save(obj);
            tx.commit();
        } catch (HibernateException e) {
        	tx.rollback();
			e.printStackTrace();
        } finally {
        }
    }

    protected void update(Object obj) {
    	session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        try {
            session.saveOrUpdate(obj);
            tx.commit();
        } catch (HibernateException e) {
        	tx.rollback();
			e.printStackTrace();
        } finally {
        }
    }

    protected void delete(Object obj) {
    	session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        try {
            session.delete(obj);
            tx.commit();
        } catch (HibernateException e) {
        	tx.rollback();
			e.printStackTrace();
        } finally {
        }
    }

    protected Object read(Class<T> clazz, PK id) {
    	session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
    	Object obj = null;
        try {
            obj = session.get(clazz, id);
            tx.commit();
        } catch (HibernateException e) {
        	tx.rollback();
			e.printStackTrace();
        } finally {
        }
        return obj;
    }

    @SuppressWarnings("unchecked")
	protected List<T> readAll(Class<T> clazz) {
    	session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
    	List<T> objects = null;
        try {
            Query query = session.createQuery("from " + clazz.getName());
            objects = query.list();
            tx.commit();
        } catch (HibernateException e) {
        	tx.rollback();
			e.printStackTrace();
        } finally {
        }
        return objects;
    }
}